/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entities.User;
import factory.DBConnectionFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author theworldiwant
 */
public class MySQLUserDAO extends UserDAO{
   
    public MySQLUserDAO(){
           try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
  
            PreparedStatement pstmt3 = conn.prepareStatement("SELECT * FROM usertypereference");
            ResultSet rs = pstmt3.executeQuery();
            int n=0;
            while(rs.next())
                n++;
            //init
            if(n==0){
                PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `webdeve`.`usertypereference` (`id`, `name`, `description`) VALUES ('1', 'admin', 'for admin')");
                PreparedStatement pstmt2 = conn.prepareStatement("INSERT INTO `webdeve`.`usertypereference` (`id`, `name`, `description`) VALUES ('2', 'common user', 'for common user')");
               
                pstmt.executeUpdate();
                pstmt2.executeUpdate();
                User user=new User();
        
                user.setId(1);
                user.setActOrPass("active");
                user.setPassword("admin");
                user.setUsername("admin");
                user.setUserTypeId(1);
                user.setGender('F');
                addUser(user);
                
            }
            conn.close();
        } catch (SQLException ex) {
           
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }  
    private int getCurId(){
            int ctr=0;
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt2;
        try {
            pstmt2 = conn.prepareStatement("select id from users");
            ResultSet rs=pstmt2.executeQuery();
            while(rs.next())
                ctr=rs.getInt("id");
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
           
            
        return ctr;
    }
    @Override
    public void addUser(User obj) {
         try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            
            PreparedStatement pstmt = conn.prepareStatement("insert into users(id,username,password,userTypeId, active, profilePic, age, gender, location, bday, shippingAddress) values (?,?,?,?,?,?,?,?,?,?,?) ");
         
            pstmt.setInt(1, getCurId()+1);
            pstmt.setString(2, obj.getUsername());
            pstmt.setString(3, this.encodePass(obj.getPassword()));
            pstmt.setInt(4, obj.getUserTypeId());
            pstmt.setString(5, obj.getActOrPass());
            pstmt.setString(6, obj.getProfilePic());
            pstmt.setInt(7, obj.getAge());
            pstmt.setString(8, obj.getGender()+"");
            pstmt.setString(9, obj.getLocation());
            pstmt.setDate(10, obj.getBday());
            pstmt.setString(11, obj.getShoppingAddress());
            pstmt.executeUpdate();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void updateUser(User obj) {

       try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("UPDATE `webdeve`.`users` SET `username`=?, `password`=?, `userTypeId`=?, `active`=?, `profilePic`=?, `age`=?, `gender`=?, `location`=?, `bday`=?, `shippingAddress`=? WHERE `id`="+obj.getId());
            pstmt.setString(1, obj.getUsername());
            pstmt.setString(2, this.encodePass(obj.getPassword()));
            pstmt.setInt(3, obj.getUserTypeId());
            pstmt.setString(4, obj.getActOrPass());
            pstmt.setString(5, obj.getProfilePic());
            pstmt.setInt(6, obj.getAge());
            pstmt.setString(7, obj.getGender()+"");
            pstmt.setString(8, obj.getLocation());
            pstmt.setDate(9, obj.getBday());
            pstmt.setString(10, obj.getShoppingAddress());
            pstmt.executeUpdate();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void activateUser(User obj) {
            
       try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("UPDATE `webdeve`.`users` SET  `active`='active' WHERE `id`="+obj.getId());
            
            pstmt.executeUpdate();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    
    

    @Override
    public void deActivateUser(User obj) {
         try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("UPDATE `webdeve`.`users` SET  `active`='passive' WHERE `id`="+obj.getId());
            
            pstmt.executeUpdate();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public User findUserByName(String s) {
      
        try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users where username=?");
            pstmt.setString(1, s);
            ResultSet rs= pstmt.executeQuery();
            User user= new User();
            while(rs.next()){
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(this.encodePass(rs.getString("password")));
                user.setUserTypeId(rs.getInt("userTypeId"));
                user.setActOrPass(rs.getString("active"));
                user.setProfilePic(rs.getString("profilePic"));
                user.setAge(rs.getInt("age"));
                user.setGender(rs.getString("gender").charAt(0));
                user.setLocation(rs.getString("location"));
                user.setBday(rs.getDate("bday"));
                user.setShoppingAddress(rs.getString("shoppingAddress"));
                
            }
            conn.close();
             return user;
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public User findUserById(String k) {
          try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users where id=?");
            pstmt.setString(1, k);
            ResultSet rs= pstmt.executeQuery();
            User user= new User();
            while(rs.next()){
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(this.encodePass(rs.getString("password")));
                user.setUserTypeId(rs.getInt("userTypeId"));
                user.setActOrPass(rs.getString("active"));
                user.setProfilePic(rs.getString("profilePic"));
                user.setAge(rs.getInt("age"));
                user.setGender(rs.getString("gender").charAt(0));
                user.setLocation(rs.getString("location"));
                user.setBday(rs.getDate("bday"));
                user.setShoppingAddress(rs.getString("shoppingAddress"));
                
            }
            conn.close();
             return user;
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public User validateUser(String username, String password) {
 
        try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users where username=? and password=?");
            pstmt.setString(1, username);
            pstmt.setString(2, this.encodePass(password));
            ResultSet rs= pstmt.executeQuery();
            User us=null;
            
            while(rs.next())
                us= new User();
            conn.close();
             return us;
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
        
    }
    private char[] getAlp(){
          char[] alp={'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 
                    'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
                    'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 
                    's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
          return alp;
    }
    private String encodePass(String pass){
        char[] alp = getAlp();
        int j=0, k=0;
        String str="";
        char[] newS = new char[pass.length()];
        for(int i=51; i>=0&&j!=pass.length(); i--){
            if(alp[i]==pass.charAt(j)){
                newS[j]=alp[k];
                j++;

            }
            k++;
        }
        for(char n: newS)
            str+=n;
        
        return str;
    }
    private String decodePass(String pass){
        char[] alp = getAlp();
         int j=0, k=0;
        String str="";
        char[] newS = new char[pass.length()];
        for(int i=51; i>=0&&j!=pass.length(); i--){
            if(alp[i]==pass.charAt(j)){
                newS[j]=alp[k];
                j++;

            }
            k++;
        }
        for(char n: newS)
            str=n+str;
        
        return str.toUpperCase();
    }
    
    
}
